const wx2my = require('../wx2my');

var dtime = '_deadtime';

function put(k, v, t) {
  wx2my.setStorageSync(k, v);
  var seconds = parseInt(t);

  if (seconds > 0) {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000 + seconds;
    wx2my.setStorageSync(k + dtime, timestamp + "");
  } else {
    wx2my.removeStorageSync(k + dtime);
  }
}

function get(k, def) {
  var deadtime = parseInt(wx2my.getStorageSync(k + dtime));

  if (deadtime) {
    if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
      if (def) {
        return def;
      } else {
        return;
      }
    }
  }

  var res = wx2my.getStorageSync(k);

  if (res) {
    return res;
  } else {
    return def;
  }
}

function remove(k) {
  wx2my.removeStorageSync(k);
  wx2my.removeStorageSync(k + dtime);
}

function clear() {
  wx2my.clearStorageSync();
}

module.exports = {
  put: put,
  get: get,
  remove: remove,
  clear: clear
};